package com.example.edu.Service.ipml;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.example.edu.Dto.*;
import com.example.edu.Entity.Article_Tag;
import com.example.edu.Mapper.ArticleMapper;
import com.example.edu.Mapper.Article_TagMapper;
import com.example.edu.Mapper.TagMapper;
import com.example.edu.Service.AllArticleService;
import com.example.edu.Utils.CacheDataBaseUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.example.edu.Utils.Constants.HOT_ARTICLES_CACHE_TTL;
import static com.example.edu.Utils.Constants.HOT_ARTICLES_KEY;

@Service
public class AllArticleServiceImpl implements AllArticleService {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    private TagMapper tagMapper;
    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private Article_TagMapper article_tagMapper;

    @Override
    public Result suggest() {
        return Result.ok(tagMapper.getStatic());
    }

    @Override
    public Result search(UnionSearchDto unionSearchDto) {
        int start = unionSearchDto.getStartIndex();
        int count = unionSearchDto.getCount();
        String put = unionSearchDto.getPut();
        Timestamp begin = unionSearchDto.getBegin();
        Timestamp end = unionSearchDto.getEnd();
        List<Integer> tags = unionSearchDto.getTags();
        List<ArticleListReturnDto> articles = articleMapper.getArticlesByUnion2(put, StrUtil.reverse(put),begin,end);
        List<ArticleListReturnDto> rs = new ArrayList<>();
        if(articles.isEmpty())
            return Result.fail("没有搜索到文章");
        if(tags.isEmpty()){
            int size = articles.size();
            if(start >= size)
                return Result.fail("这一页还没有文章");
            rs = articles.subList(start,Math.min(start+count+1,size));
            for(int i = 0;i < rs.size();i++){
                ArticleListReturnDto r = rs.get(i);
                r.setIndex(i);
                r.setTags(article_tagMapper.getTagNames(r.getArticle_id()));
            }
            return Result.ok(new ListReturnDto(size,rs));
        }
        List<Integer> article_ids = new ArrayList<>();
        for (ArticleListReturnDto article : articles)
            article_ids.add(article.getArticle_id());
        List<Article_Tag> relations = article_tagMapper.getRelations(article_ids);
        int i = 0;
        for (ArticleListReturnDto article : articles){
            List<Integer> tag_ids = new ArrayList<>();
            for(;i < relations.size();i++){
                if (article.getArticle_id() != relations.get(i).getArticle_id())
                    break;
                tag_ids.add(relations.get(i).getTag_id());
            }
            if(tag_ids.containsAll(tags)) {
                article.setTag_ids(tag_ids);
                rs.add(article);
            }
        }
        if(rs.isEmpty())
            return Result.fail("没有搜索到文章");
        int size = rs.size();
        if(start >= size)
            return Result.fail("这一页还没有文章");
        rs = rs.subList(start,Math.min(start+count+1,size));
        for(int j = 0;j < rs.size();j++){
            ArticleListReturnDto r = rs.get(j);
            r.setIndex(j);
            r.setTags(tagMapper.getTagNames(r.getTag_ids()));
        }
        return Result.ok(new ListReturnDto(size,rs));
    }

    @Override
    public Result getHot() {
        List<String> hot_articles = stringRedisTemplate.opsForList().range(HOT_ARTICLES_KEY,0,-1);
        if(hot_articles != null){
            List<ArticleListReturnDto> rs = new ArrayList<>();
            for(String hot_article : hot_articles)
                rs.add(JSONUtil.toBean(hot_article, ArticleListReturnDto.class));
            return Result.ok(rs);
        }
        List<ArticleListReturnDto> rs = articleMapper.getHot();
        if(rs.isEmpty())
            return Result.fail("没有热点文章");
        for(ArticleListReturnDto returnDto : rs) {
            returnDto.setTags(article_tagMapper.getTagNames(returnDto.getArticle_id()));
            stringRedisTemplate.opsForList().rightPush(HOT_ARTICLES_KEY, JSONUtil.toJsonStr(returnDto));
        }
        stringRedisTemplate.expire(HOT_ARTICLES_KEY,HOT_ARTICLES_CACHE_TTL, TimeUnit.HOURS);
        return Result.ok(rs);
    }

    @Override
    public Result getList(PageDto pageDto) {
        int start_index = pageDto.getStartIndex();
        int count = pageDto.getCount();
        int total = articleMapper.getAllArticleNums();
        if(total == 0)
            return Result.fail("还没有文章");
        List<ArticleListReturnDto> articles = articleMapper.getALLArticles(start_index-1,Math.min(count,total-start_index+1));
        if(articles == null)
            return Result.fail("这一页还没有文章哟");
        for(int i = 0;i < articles.size();i++){
            ArticleListReturnDto article = articles.get(i);
            article.setIndex(i);
            article.setTags(article_tagMapper.getTagNames(article.getArticle_id()));
        }
        ListReturnDto r = new ListReturnDto(total,articles);
        return Result.ok(r);
    }

    @Override
    public Result getTags() {
        return Result.ok(tagMapper.getAllTags());
    }
}
